package net.hvacapp.cmvrfforandroid.ui.project;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.mirror.android.common.util.StringUtils;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.constant.Constant;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.manager.ProjectManager;
import net.hvacapp.cmvrfforandroid.ui.BaseActivity;
import net.hvacapp.cmvrfforandroid.ui.MainTabBarActivity;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetIndoorEquipDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetKqnrsjDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetProductDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GuidData;
import net.hvacapp.cmvrfforandroid.ui.project.model.ProjectInfoData;
import net.hvacapp.cmvrfforandroid.ui.project.model.KqnrsjData;
import net.hvacapp.cmvrfforandroid.ui.project.model.RoomData;
import net.hvacapp.cmvrfforandroid.ui.project.view.DeviceItemView;
import net.hvacapp.cmvrfforandroid.utils.AnnotationUtil;
import net.hvacapp.cmvrfforandroid.utils.NumberUtil;
import net.hvacapp.cmvrfforandroid.widget.CellSeperateLineView;
import net.hvacapp.cmvrfforandroid.widget.IOSAlertView;
import net.hvacapp.cmvrfforandroid.widget.ItemSelectionView;
import net.hvacapp.cmvrfforandroid.widget.ProjectActionView;
import net.hvacapp.cmvrfforandroid.widget.UserSelectionView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@EActivity(R.layout.activity_project_step7)
public class ProjectStep7Activity extends BaseActivity {

    private final int Select_KQNRSJ = 1;
    private final int Select_KQNRSJ_Xl = 2;

    @ViewById(R.id.action_view)
    ProjectActionView mActionView;


    private Dialog mProgressDlg;

    @ViewById(R.id.lv_templete)
    ListView mTempleteLv;

    private QuickAdapter<KqnrsjData> mQuickAdapter;

    private ArrayList<KqnrsjData> mKqnrsjData;

    private KqnrsjData mCurrentKQNRSJ;

    private List<GuidData> mCandiData; //可选型式



    /**
     * 页面加载完后执行
     */
    @AfterViews
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        initViews();
        initEvent();
    }

    /***
     * 初始化视图
     */
    private void initViews() {
        mActionView.setActionInfo(ProjectManager.getInstance().getTotal(), ProjectManager.getInstance().getCurrent());
    }

    /**
     * 初始化
     */
    @Override
    public void initBoot() {
        mKqnrsjData = new ArrayList<>();
        mCandiData = null;

        setupToolbar(R.string.title_for_project, "空气能热水机配置", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(AnnotationUtil.get(MainTabBarActivity.class));
            }
        });

//        int ids[] = {R.id.action_new_kqnrsj};
//        int icons[] = {R.drawable.new_project};
//        setupToolbarMenuItem(ids, icons, new String[]{"新建"}, null);
        setButton1Info("新建", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addOneProjectKQNRSJInfo();
            }
        });

        if (mQuickAdapter == null){
            mQuickAdapter = new QuickAdapter<KqnrsjData>(context, R.layout.kqnrsj_config_cell_item) {
                @Override
                protected void convert(final BaseAdapterHelper helper, final KqnrsjData item) {
                    LinearLayout KQNRSJInfoLl = helper.getView(R.id.ll_kqnrsj_info);
                    KQNRSJInfoLl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //控制显示隐藏
                            item.setClosed(!item.isClosed());
                            if (item.isClosed()) {
                                helper.setImageResource(R.id.iv_selected_mark, R.drawable.arrow_down);
                                helper.setVisible(R.id.ll_kqnrsj_content, false);
                            } else {
                                helper.setImageResource(R.id.iv_selected_mark, R.drawable.arrow_up);
                                helper.setVisible(R.id.ll_kqnrsj_content, true);
                            }
                        }
                    });

                    helper.setText(R.id.tv_title, item.getName());
                    helper.setText(R.id.tv_description, "总用水量：" + NumberUtil.formateDouble(item.getWaterConsTotal()) + "L");

                    TextView deleteTv = helper.getView(R.id.tv_delete);
                    deleteTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //删除

                            Map<String, Object> param = new HashMap<>();
                            param.put("kiid", item.getGuidId());

                            BasicHttpClient.httpDeleteAsync(HttpConstant.HTTP_DELETE_PROJECT_ONE_KQNRSJ, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetKqnrsjDataResp>() {
                                @Override
                                public void onSuccess(GetKqnrsjDataResp obj) {
                                    //需要重新拉取所有的系统数据
                                    mQuickAdapter.remove(item);
                                    mKqnrsjData.remove(item);
                                }

                                @Override
                                public void onFailure(String response) {
                                    showMessage("删除空气能热水机系统失败！");
                                }
                            });
                        }
                    });

                    //浴缸数
                    final DeviceItemView yugang = helper.getView(R.id.dv_yugang);
                    yugang.setDeviceString("浴缸数");
                    yugang.setCount(item.getYugangCount(), "个");
                    yugang.deleteBtnDismiss();

                    yugang.setOnMinusClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int count = yugang.getCount();
                            if (count > 0) {
                                count--;
                            } else {
                                return;
                            }
                            item.setYugangCount(count);
                            yugang.setCount(count, "个");
                            //修改数量
                            modifyProjectKQNRSJInfo(item);

                        }
                    });
                    yugang.setOnAddClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int count = yugang.getCount();
                            count++;
                            item.setYugangCount(count);
                            yugang.setCount(count, "个");
                            //修改数量
                            modifyProjectKQNRSJInfo(item);
                        }
                    });

                    //人数
                    final DeviceItemView person = helper.getView(R.id.dv_person);
                    person.setDeviceString("人数");
                    person.setCount(item.getPeople(), "人");
                    person.deleteBtnDismiss();

                    person.setOnMinusClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int count = person.getCount();
                            if (count > 0) {
                                count--;
                            } else {
                                return;
                            }
                            item.setPeople(count);
                            person.setCount(count, "人");
                            //修改数量
                            modifyProjectKQNRSJInfo(item);

                        }
                    });
                    person.setOnAddClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int count = person.getCount();
                            count++;
                            item.setPeople(count);
                            person.setCount(count, "人");
                            //修改数量
                            modifyProjectKQNRSJInfo(item);
                        }
                    });

                    //人均用水量
                    final UserSelectionView waterSel = helper.getView(R.id.sel_water);
                    waterSel.setTitleString("人均用水量");
                    if (item.getWaterConsPer() < 40) {
                        waterSel.setInfoString("未选择");
                    }
                    else {
                        waterSel.setInfoString(NumberUtil.formatInt((int)item.getWaterConsPer()) + "L");
                    }
                    waterSel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //选择用水量
                            String[] items = ProjectStep7Activity.this.getResources().getStringArray(
                                    R.array.waterArray);
                            new AlertDialog.Builder(ProjectStep7Activity.this)
                                    .setTitle("选择人均用水量")
                                    .setItems(items, new DialogInterface.OnClickListener() {

                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            switch (which) {
                                                case 0:
                                                    item.setWaterConsPer(40);
                                                    break;
                                                case 1:
                                                    item.setWaterConsPer(50);
                                                    break;
                                                case 2:
                                                    item.setWaterConsPer(60);
                                                    break;
                                                case 3:
                                                    item.setWaterConsPer(70);
                                                    break;
                                                default:
                                                    item.setWaterConsPer(80);
                                                    break;
                                            }
                                            waterSel.setInfoString(NumberUtil.formatInt((int)item.getWaterConsPer()) + "L");
                                            //修改项目信息
                                            modifyProjectKQNRSJInfo(item);
                                        }
                                    })
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    })
                                    .show();
                        }
                    });

                    //选择空气能热水机
                    UserSelectionView selectionView = helper.getView(R.id.sel_kqnrsj);
                    selectionView.setTitleString("空气能热水机");
                    selectionView.setInfoString("请选择");

                    selectionView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //选择空气能热水机设备
                            mCurrentKQNRSJ = item;
                            Intent intent = new Intent(ProjectStep7Activity.this, AnnotationUtil.get(SelectDeviceXsActivity.class));
                            Bundle bundle = new Bundle();
                            bundle.putBoolean("multiple", false);
                            bundle.putString("tag", ProjectInfoData.MACHINE_TAG_FOR_KQNRSJ);
                            intent.putExtras(bundle);
                            startActivityForResult(intent, Select_KQNRSJ);
                        }
                    });

                    //自动选型
                    TextView autoTv = helper.getView(R.id.tv_kqnrsj);
                    autoTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //自动选型点击
                            mCurrentKQNRSJ = item;
                            if (mCandiData != null && mCandiData.size() == 1) {
                                //只有一个系列时，直接开始自动选型
                                ProjectManager.getInstance().setProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_KQNRSJ, mCandiData.get(0).getGuidId());
                                getKQNRSJDefaultDevice(mCurrentKQNRSJ);
                                return;
                            }
                            Intent intent = new Intent(ProjectStep7Activity.this, AnnotationUtil.get(SelectXsActivity.class));
                            Bundle bundle = new Bundle();
                            bundle.putBoolean("multiple", false);
                            bundle.putString("tag", ProjectInfoData.MACHINE_TAG_FOR_KQNRSJ);
                            intent.putExtras(bundle);
                            startActivityForResult(intent, Select_KQNRSJ_Xl);
                        }
                    });

                    //添加设备
                    LinearLayout KQNRSJContent = helper.getView(R.id.ll_device);
                    KQNRSJContent.removeAllViews();

                    CellSeperateLineView line = new CellSeperateLineView(ProjectStep7Activity.this);
                    KQNRSJContent.addView(line);

                    final DeviceItemView itemView = new DeviceItemView(ProjectStep7Activity.this);

                    if (StringUtils.isEmpty(item.getKqnRsjId()) || StringUtils.isEquals(item.getKqnRsjId(), Constant.EMPTY_DEVICE_ID)) {
                        itemView.setDeviceString("请选择");
                    }
                    else {
                        itemView.setDeviceString(item.getXh());
                    }
                    itemView.setCount(item.getCount());
                    itemView.deleteBtnDismiss();

                    itemView.setOnMinusClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int count = itemView.getCount();
                            if (count > 1) {
                                count--;
                            } else {
                                return;
                            }
                            item.setCount(count);
                            itemView.setCount(count);
                            //修改数量
                            modifyProjectKQNRSJInfo(item);

                        }
                    });
                    itemView.setOnAddClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int count = itemView.getCount();
                            count++;
                            item.setCount(count);
                            itemView.setCount(count);
                            //修改数量
                            modifyProjectKQNRSJInfo(item);
                        }
                    });
                    KQNRSJContent.addView(itemView);

                }
            };
        }

        mTempleteLv.setAdapter(mQuickAdapter);
    }

    /**
     * toolbar上的按钮点击事件
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_new_kqnrsj:
                addOneProjectKQNRSJInfo();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 初始化数据
     */
    @Override
    public void initData(Intent intent) {
        loadProjectKqnrsjInfo();
        loadProjectSelectedSeries();
    }



    /**
     * 页面名称
     */
    @Override
    public String getName() {
        return "";
    }

    private void initEvent() {
        mActionView.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //上一步
                ProjectManager.getInstance().goLastStep();
                finish();
            }
        });

        mActionView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下一步
                ProjectManager.getInstance().goNextStep();
                startActivity(AnnotationUtil.get(ProjectStep8Activity.class));
            }
        });

    }


    /**
     *  获取项目中空气能热水机的配置
     */
    private void loadProjectKqnrsjInfo() {
        Map<String, Object> param = new HashMap<>();
        param.put("pid", ProjectManager.getInstance().getProjectData().getGuidId());

        mProgressDlg = createProgressBarDialog(this, "数据加载中...");
        mProgressDlg.show();
        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_KQNRSJ, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetKqnrsjDataResp>() {
            @Override
            public void onSuccess(GetKqnrsjDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                mKqnrsjData.clear();
                mQuickAdapter.clear();
                mKqnrsjData.addAll(obj.getGetKqnRsjInfosResult());
                mQuickAdapter.addAll(obj.getGetKqnRsjInfosResult());
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                showMessage("获取空气能热水机信息失败，请重试！");
            }
        });

    }

    /**
     *  获取项目中选择了的系列
     */
    private void loadProjectSelectedSeries() {
        Map<String, Object> param = new HashMap<>();
        param.put("pid", ProjectManager.getInstance().getProjectData().getGuidId());
        param.put("tag", ProjectInfoData.MACHINE_TAG_FOR_KQNRSJ);

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_PRODUCT_SERIES, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetProductDataResp>() {
            @Override
            public void onSuccess(GetProductDataResp obj) {
                // 成功
                if (obj.getGetCandidateXlsResult() != null && obj.getGetCandidateXlsResult().size() > 0) {
                    mCandiData = obj.getGetCandidateXlsResult();
                }
            }

            @Override
            public void onFailure(String response) {
//                showMessage("获取系列失败，请重试！");
            }
        });
    }


    /**
     * 修改空气能热水机的信息
     * @param data
     */
    private void modifyProjectKQNRSJInfo(KqnrsjData data) {
        Map<String, Object> param = new HashMap<>();
        param.put("kqnrsjInfoData", data);

        BasicHttpClient.httpPostAsync(HttpConstant.HTTP_PUT_PROJECT_ONE_KQNRSJ, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetKqnrsjDataResp>() {
            @Override
            public void onSuccess(GetKqnrsjDataResp obj) {
                //需要重新拉取所有的系统数据
                loadProjectKqnrsjInfo();
            }

            @Override
            public void onFailure(String response) {
                showMessage("修改空气能热水机系统失败！");
            }
        });

    }

    /**
     * 修改空气能热水机的房间信息
     * @param data
     */
    private void modifyAndLoadProjectKQNRSJInfo(KqnrsjData data) {
        Map<String, Object> param = new HashMap<>();
        param.put("kqnrsjInfoData", data);

        BasicHttpClient.httpPostAsync(HttpConstant.HTTP_POST_PROJECT_ONE_KQNRSJ, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetKqnrsjDataResp>() {
            @Override
            public void onSuccess(GetKqnrsjDataResp obj) {
                //需要重新拉取所有的系统数据
                loadProjectKqnrsjInfo();
            }

            @Override
            public void onFailure(String response) {
                showMessage("修改空气能热水机系统失败！");
            }
        });

    }

    /**
     *  添加一套空气能热水机系统
     */
    private void addOneProjectKQNRSJInfo() {
        String url = HttpConstant.HTTP_PUT_PROJECT_ONE_KQNRSJ
                + "?tk=" + AccountManager.getInstance().getToken()
                + "&pid=" + ProjectManager.getInstance().getProjectData().getGuidId();

        final KqnrsjData data = new KqnrsjData();
        ArrayList<String> rm = new ArrayList<>();

        data.setGuidId(null);
        int count = mKqnrsjData.size() + 1;
        data.setName("系统" + count);
        data.setKqnRsjId(Constant.EMPTY_DEVICE_ID);
        data.setXh(null);

        mProgressDlg = createProgressBarDialog(this, "添加新配置中...");
        mProgressDlg.show();


        Map<String, Object> param = new HashMap<>();
        param.put("kqnrsjInfoData", data);

        BasicHttpClient.httpPutAsync(url, param, new HttpCallbackHandle<GetKqnrsjDataResp>() {
            @Override
            public void onSuccess(GetKqnrsjDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                data.setGuidId(obj.getCreateKqnRsjInfoResult());
                mKqnrsjData.add(data);
                mQuickAdapter.add(data);
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                showMessage("添加空气能热水机失败，请重试！");
            }
        });
    }

    /***
     * 对空气能热水机自动选型
     */
    private void getKQNRSJDefaultDevice(final KqnrsjData data) {
        if (StringUtils.isEmpty(ProjectManager.getInstance().getProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_KQNRSJ))) {
            IOSAlertView.showAlertView(ProjectStep7Activity.this, "提示", "没有获取到默认型式，自动选型失败！", "确认", null);
            return;
        }

        mProgressDlg = createProgressBarDialog(ProjectStep7Activity.this, "自动选型中...");
        mProgressDlg.show();
        Map<String, Object> param = new HashMap<>();
        param.put("kiid", data.getGuidId());
        param.put("xsid", ProjectManager.getInstance().getProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_KQNRSJ));

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_KQNRSJ_DEFAULT_DEVICE, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetKqnrsjDataResp>() {
            @Override
            public void onSuccess(GetKqnrsjDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                if (obj.getAutoKqnRsjEquipResult() != null) {
                    mQuickAdapter.remove(data);
                    mKqnrsjData.remove(data);
                    mQuickAdapter.add(obj.getAutoKqnRsjEquipResult());
                    mKqnrsjData.add(obj.getAutoKqnRsjEquipResult());
                } else {
                    IOSAlertView.showAlertView(ProjectStep7Activity.this, "提示", "超出该系列能力范围，请选择其他合适型式。", "确认", null);
                }
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                IOSAlertView.showAlertView(ProjectStep7Activity.this, "提示", "超出该系列能力范围，请选择其他合适型式。", "确认", null);
            }
        });
    }



    /**
     * 回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != this.RESULT_OK) {
            return;
        }
        if (requestCode == Select_KQNRSJ) {
            if (data != null) {
                ArrayList<GuidData> arrayData = data.getParcelableArrayListExtra("device");
                if (arrayData != null && arrayData.size() > 0) {
                    GuidData selectData = arrayData.get(0);
                    mCurrentKQNRSJ.setKqnRsjId(selectData.getGuidId());
                    mCurrentKQNRSJ.setXh(selectData.getName());
                    mCurrentKQNRSJ.setCount(1);
                    modifyAndLoadProjectKQNRSJInfo(mCurrentKQNRSJ);
                }
            }
        }
        else if (requestCode == Select_KQNRSJ_Xl) {
            if (data != null) {
                List<GuidData> xl = data.getParcelableArrayListExtra("device");
                if (xl != null && xl.size() > 0) {
                    //开始自动选型
                    ProjectManager.getInstance().setProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_KQNRSJ, xl.get(0).getGuidId());
                    getKQNRSJDefaultDevice(mCurrentKQNRSJ);
                }
            }
        }
    }

}
